//
//  ACLiveInfoEditViewController.m
//  ACLiteAVUISDK
//
//  Created by 冯琰琰 on 2021/3/30.
//

#import "ACLiveInfoEditViewController.h"
#import <Photos/PHPhotoLibrary.h>
@interface ACLiveInfoEditViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>


@property(nonatomic,strong)UIButton *uploadBtn;
@property(nonatomic,strong)UIImagePickerController *picker;

@end

@implementation ACLiveInfoEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = UIColorFromRGB(0xF4F5F8);
    self.title = @"简介编辑";
    [self setUI];
}
-(void)setUI{
    UIView *contentBgView = [[UIView alloc] init];
    contentBgView.backgroundColor = UIColorFromRGB(0xffffff);
    [self.view addSubview:contentBgView];
    [contentBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_offset(10);
    }];
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"简介标题";
    titleLabel.textAlignment = NSTextAlignmentLeft;
    titleLabel.textColor = UIColorFromRGB(0x606266);
    titleLabel.font = [UIFont systemFontOfSize:14];
    [contentBgView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.top.mas_offset(10);
    }];
    
    UITextView *titleTextView = [[UITextView alloc] init];
    titleTextView.text = self.info_title;
    if (self.info_title.length == 0) {
        [titleTextView wgk_addPlaceHolder:@"输入简介标题"];
    }
    titleTextView.wgk_placeHolderTextView.font = [UIFont systemFontOfSize:14];
    titleTextView.wgk_placeHolderTextView.textColor = UIColorFromRGB(0xC0C4CC);
    [contentBgView addSubview:titleTextView];
    [titleTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.equalTo(titleLabel.mas_bottom).offset(2);
        make.height.mas_equalTo(33);
    }];
    
    UIView *line1 = [[UIView alloc] init];
    line1.backgroundColor = UIColorFromRGB(0xE2E1E0);
    [contentBgView addSubview:line1];
    [line1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.height.mas_equalTo(0.5);
        make.right.mas_equalTo(0);
        make.top.equalTo(titleTextView.mas_bottom).offset(10);
    }];
    
    UILabel *imageLabel = [[UILabel alloc] init];
    imageLabel.text = @"简介图片";
    imageLabel.textAlignment = NSTextAlignmentLeft;
    imageLabel.textColor = UIColorFromRGB(0x606266);
    imageLabel.font = [UIFont systemFontOfSize:14];
    [contentBgView addSubview:imageLabel];
    [imageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.top.equalTo(line1.mas_bottom).offset(10);
    }];
    
    self.uploadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    if ([self.info_cover isEqualToString:@""] || self.info_cover == nil) {
        [self.uploadBtn setImage:[UIImage imageWithName:@"icon_live_uploadImage" bundle:ACLiteAVUISDK targetClass:[self class]] forState:UIControlStateNormal];
    }else{
        if ((![self.info_cover startsWith:@"http://"] && ![self.info_cover startsWith:@"https://"]) && self.info_cover != nil) {
            self.info_cover = [@"http://" stringByAppendingString:self.info_cover];
        }
        [self.uploadBtn sd_setImageWithURL:[NSURL URLWithString:self.info_cover] forState:UIControlStateNormal];
    }
    [contentBgView addSubview:self.uploadBtn];
    [self.uploadBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.size.mas_equalTo(CGSizeMake(116, 65));
        make.top.equalTo(imageLabel.mas_bottom).offset(36);
    }];

    
    UIView *line2 = [[UIView alloc] init];
    line2.backgroundColor = UIColorFromRGB(0xE2E1E0);
    [contentBgView addSubview:line2];
    [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.height.mas_equalTo(0.5);
        make.right.mas_equalTo(0);
        make.top.equalTo(self.uploadBtn.mas_bottom).offset(12);
    }];
    
    UILabel *contentLabel = [[UILabel alloc] init];
    contentLabel.text = @"简介内容";
    contentLabel.textAlignment = NSTextAlignmentLeft;
    contentLabel.textColor = UIColorFromRGB(0x606266);
    contentLabel.font = [UIFont systemFontOfSize:14];
    [contentBgView addSubview:contentLabel];
    [contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.top.equalTo(line2.mas_bottom).offset(10);
    }];
    
    UITextView *contentTextView = [[UITextView alloc] init];
    contentTextView.text = self.info_desc;
    if (self.info_desc.length == 0) {
        [contentTextView wgk_addPlaceHolder:@"输入简介内容"];
    }
    contentTextView.wgk_maxLength = 1000;
    contentTextView.wgk_placeHolderTextView.font = [UIFont systemFontOfSize:14];
    contentTextView.wgk_placeHolderTextView.textColor = UIColorFromRGB(0xC0C4CC);
    [contentBgView addSubview:contentTextView];
    [contentTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.equalTo(contentLabel.mas_bottom).offset(2);
        make.height.mas_equalTo(230);
    }];
    
    UILabel *contenLength = [[UILabel alloc] init];
    contenLength.textAlignment = NSTextAlignmentRight;
    [contentBgView addSubview:contenLength];
    [contenLength mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-15);
        make.bottom.equalTo(contentBgView.mas_bottom).offset(-10);
        make.top.equalTo(contentTextView.mas_bottom).offset(10);
    }];

    RAC(contenLength,attributedText) = [[RACObserve(contentTextView, text) merge:contentTextView.rac_textSignal] map:^id _Nullable(NSString*  _Nullable value) {
        NSString *Str = [NSString stringWithString:[value stringByReplacingOccurrencesOfString:@" " withString:@""]];
        NSString *length = [NSString stringWithFormat:@"%lu",(unsigned long)Str.length];
        NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:length attributes:@{
            NSFontAttributeName:[UIFont systemFontOfSize:14.0],NSForegroundColorAttributeName:UIColorFromRGB(0xFF6048)
        }];
        [attributedStr appendAttributedString:[[NSAttributedString alloc] initWithString:@"/1000" attributes:@{
            NSFontAttributeName:[UIFont systemFontOfSize:14.0],NSForegroundColorAttributeName:UIColorFromRGB(0x909399)
        }] ];
        return attributedStr;
    }];
    
    UIView *footerBgView = [[UIView alloc] init];
    footerBgView.backgroundColor = UIColorFromRGB(0xffffff);
    [self.view addSubview:footerBgView];
    [footerBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(0);
        make.height.mas_equalTo(ACSafeAreaBottomHeight + 68);
    }];
    CGFloat btnWidth = (ACSCREEN_WIDTH - 45)/2.0;
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelBtn.backgroundColor = UIColorFromRGB(0xF4F5F8);
    cancelBtn.layer.masksToBounds = YES;
    cancelBtn.layer.cornerRadius = 22;
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:UIColorFromRGB(0xFF6048) forState:UIControlStateNormal];
    [cancelBtn.titleLabel setFont:[UIFont systemFontOfSize:16 weight:UIFontWeightMedium]];
    [footerBgView addSubview:cancelBtn];
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.height.mas_equalTo(48);
        make.top.mas_offset(10);
        make.width.mas_equalTo(btnWidth);
    }];
    
    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    saveBtn.backgroundColor = UIColorFromRGB(0xFF6048);
    saveBtn.layer.masksToBounds = YES;
    saveBtn.layer.cornerRadius = 22;
    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    [saveBtn setTitleColor:UIColorFromRGB(0xffffff) forState:UIControlStateNormal];
    [saveBtn.titleLabel setFont:[UIFont systemFontOfSize:16 weight:UIFontWeightMedium]];
    [footerBgView addSubview:saveBtn];
    [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-15);
        make.width.height.top.equalTo(cancelBtn);
    }];
    
    
    @weakify(self);
    RACDelegateProxy *delegateProxy = [[RACDelegateProxy alloc]initWithProtocol:@protocol(UITextViewDelegate)];
    [[delegateProxy rac_signalForSelector:@selector(textViewDidEndEditing:)] subscribeNext:^(RACTuple *args) {
        DDLogInfo(@"%@",[args first]);
        UITextView *textView = [args first];
        if (textView == contentTextView) {
            self.info_desc = textView.text;
        }else{
            self.info_title = textView.text;
        }
    }];
    contentTextView.delegate = (id<UITextViewDelegate>)delegateProxy;
    objc_setAssociatedObject(contentTextView, _cmd, delegateProxy, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
    titleTextView.delegate = (id<UITextViewDelegate>)delegateProxy;
    objc_setAssociatedObject(contentTextView, _cmd, delegateProxy, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
 
    [[cancelBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    [[saveBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        DDLogInfo(@"info_title------------------%@",self.info_title);
        DDLogInfo(@"info_desc-------------------%@",self.info_desc);
        DDLogInfo(@"info_cover------------------%@",self.info_cover);
        if (self.finishedHandler) {
            self.finishedHandler(self.info_title, self.info_cover, self.info_desc);
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
    
    [[self.uploadBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        [self showImagePicker];
    }];
}
-(void)showImagePicker{
    @weakify(self);
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"上传封面" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancelBtn = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
       // 从相册选取
        @strongify(self)
        [self chooseFromAlbum];
    }];
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
       // 拍照
        @strongify(self)
        [self takePhoto];
    }];
    [alertVC addAction:cancelBtn];
    [alertVC addAction:albumAction];
    [alertVC addAction:cameraAction];
    [self presentViewController:alertVC animated:YES completion:nil];
}

-(void)takePhoto{
//    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
//    if (status == PHAuthorizationStatusDenied || status == PHAuthorizationStatusRestricted) {
//        // 没有权限
//        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请在iPhone的设置-隐私-相机中允许访问相机" preferredStyle:UIAlertControllerStyleActionSheet];
//        UIAlertAction *cancelBtn = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        }];
//        [alertVC addAction:cancelBtn];
//        [self presentViewController:alertVC animated:YES completion:nil];
//    }else if (status == PHAuthorizationStatusNotDetermined){
//        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
//            if (granted) {
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [self takePhoto];
//                });
//            }
//        }];
//    }else{
        // 有权限
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            self.picker = [[UIImagePickerController alloc] init];
            [self.picker setSourceType:UIImagePickerControllerSourceTypeCamera];
            [self.picker setAllowsEditing:YES];
            [self.picker setDelegate:self];
            [self presentViewController:self.picker animated:YES completion:nil];
        }else{
            DDLogInfo(@"照片源不可用");
        }
//    }
}
-(void)chooseFromAlbum{
//    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
//    if (status == PHAuthorizationStatusDenied || status == PHAuthorizationStatusRestricted) {
//        // 没有权限
//        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请在iPhone的设置-隐私-相册中允许访问相册" preferredStyle:UIAlertControllerStyleActionSheet];
//        UIAlertAction *cancelBtn = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        }];
//        [alertVC addAction:cancelBtn];
//        [self presentViewController:alertVC animated:YES completion:nil];
//    }else if (status == PHAuthorizationStatusNotDetermined){
//        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
//            if (granted) {
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [self takePhoto];
//                });
//            }
//        }];
//    }else{
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            self.picker = [[UIImagePickerController alloc] init];
            [self.picker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            [self.picker setAllowsEditing:YES];
            [self.picker setDelegate:self];
            [self presentViewController:self.picker animated:YES completion:nil];
        }else{
            DDLogInfo(@"照片源不可用");
        }
//    }
}
#pragma mark - UIImagePickerControllerDelegate UINavigationControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
   [picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info{
    NSString* type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        UIImage* edit = [info objectForKey:UIImagePickerControllerEditedImage];
        NSData *imageData = UIImagePNGRepresentation(edit);
        CIImage *ciiimage = [CIImage imageWithData:imageData];
        CIContext *context = [CIContext context];
        if (@available(iOS 10.0, *)) {
            NSData *jpgData = [context JPEGRepresentationOfImage:ciiimage colorSpace:[ciiimage colorSpace] options:[NSDictionary dictionary]];
            UIImage *image = [UIImage imageWithData:jpgData];
            NSData *data_upload = UIImageJPEGRepresentation(image, 0.1);
            [SVProgressHUD showWithStatus:@"正在上传"];
            [ACLiveRoomManager uploadImageWithImageData:data_upload success:^(id  _Nonnull responseObject) {
                DDLogInfo(@"%@",responseObject);
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD showSuccessWithStatus:@"上传完成"];
                });
                self.info_cover = [responseObject objectForKey:@"file_url"];
                [self.uploadBtn setImage:image forState:UIControlStateNormal];
            }];
        } else {
            // Fallback on earlier versions
        }
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}

@end
